/**
 * @Description:
 * @author 紫霞
 * @since 2019/1/17
 */
// React基础组件
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
// 引入antd的组件
import { Row, Col, Card, Button, Tabs, Form, Input,Popconfirm, Modal, Tooltip,Pagination} from 'antd'
//导入路由组件，用于跳转等
import { Link, hashHistory } from 'dva/router'
// 导入项目全局配置文件
import config from 'config/config'

// 引入model取值工具方法
import { mapStateToProps } from 'utils/view_utils'
//引用listPage
import ListPage from 'widget/PageTmpl/ListPage'

// 当前组件样式
import styles from './advertiseListStyle.less'
import classnames from 'classnames/bind';
let cx = classnames.bind(styles);

import { Grid, QueryCondition } from 'widget/Grid/index'
import { AdvanceSearch } from 'widget/CollapsiblePanels/index'
import { chunk,set,get } from 'lodash'
import Uploader from "../../../widget/Upload";
import CollapsiblePanels from 'widget/CollapsiblePanels/CollapsiblePanels'
const FormItem = Form.Item;
const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 },
}
const formItemLayout01 = {
  labelCol: { span: 4 },
  wrapperCol: { span: 4 },
}

/**
 * description 路由视图及事件处理
 * dispatch 分发到models中的effects对应事件名
 * model 用于获取models中state定义的数据
 * form 表单对象
 */

const routeView = function ({dispatch, model, form}) {
  // 表单的子函数
  const {resetFields, getFieldDecorator, validateFields, setFieldsValue} = form
  // 取出model对象，命名空间
  const {modelObj, namespace} = model
  let {loading, btnLoading, modalObj, currentItem, queryList, tableData, pageConfig,channelIndex,pageInfo=[],newBannerList=[],bannerList=[],} = modelObj
  // modelObj.xxx获取model中状态机的值
  console.log('modelObj', modelObj)
  // 点击处理事件
  const clickHandler = (e) => {
    // 分发到model文件中effects的xxx方法
    dispatch({
      type: `${namespace}/xxx`,
      payload: {}
    })
  }


  // 订单编号 seckillOrderId  项目名称 projectName 类型 productType  详情 detail  活动名称 activeName 订单类型 orderTyp 状态 status 客户姓名 accountName  创建订单时间
  const columns = [
    {
      title: '省份城市', dataIndex: 'cityName', key: 'cityName',
      width:150,
      render: (text, item, index) => {
        return `${item.provinceName||''}${item.provinceName&&item.cityName&&' - '||''}${item.cityName||''}`
      }
    },
    {title: '推荐楼盘', dataIndex: 'productName', key: 'productName'},
    {title: '推荐人', dataIndex: 'recommendUser', key: 'recommendUser'},
    {title: '推荐人手机', dataIndex: 'referrerMobile', key: 'referrerMobile'},
    {title: '推荐人类型', dataIndex: 'recommendUserType', key: 'recommendUserType'},
    {title: '指定置业顾问', dataIndex: 'consultant', key: 'consultant'},
    {title: '推荐状态', dataIndex: 'recommendStatus', key: 'recommendStatus',
      render (value, item, index){
        return {'0':'失败','1' :'成功'}[value]
      }
    },
    {title: '推荐时间', dataIndex: 'recommendTime', key: 'recommendTime', },
    {title: '客户姓名', dataIndex: 'clientName', key: 'clientName'},
    {title: '客户电话', dataIndex: 'clientPhone', key: 'clientPhone'},
    {title: '剩余保护期', dataIndex: 'protectDate', key: 'protectDate'},
    {title: '客户状态', dataIndex: 'statusName', key: 'statusName',
      // render (value, item, index) {
      //   return {'10':'待跟进','20':'验证通过','30':'已跟进','40':'已认筹','50':'已认购','60':'已签约','70':'已结算','80':'已作废','90':'已关闭'}[value]
      // }
    },
  ]
  // 表格模板配置
  const gridProps = {
    nameSpace: namespace,
    data: {
      // columns: [].concat(columns, generateAction()),
      columns: columns,
      pageConfig, tableData
    },
    pageChange: (pageNo, pageSize) => {
      console.log(pageNo, pageSize)
      dispatch({ type: `${namespace}/pageChange`, payload: {pageNo, pageSize }});
    },
    scroll: {x: 800},
    loading
  }

  // 表格操作区域
  function generateAction () {
    return {
      title: '操作',
      key: 'operation',
      fixed: 'right',
      width: 200,
      render: (data, record, index) => {
        return (
          <span>
            <a onClick={() => updateModal({item: record, index})}>详情</a>{<span className="ant-divider"/>}
          </span>
        )
      }
    }
  }



  // 弹窗
  function updateModal ({item, index} = {}) {
    modalObj.visible = !modalObj.visible
    currentItem = item
    console.log('updateModal', item, index)
    changeState({modalObj})
    if (item) {
      dispatch({
        type: `${namespace}/getDetail`,
        payload: {id: item.seckillOrderId, index}
      })
    }
  }
  

  //修改状态
  const changeState = (payload) => {
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {...payload}
    })
  }
  //修改状态
  // const inputChange = (payload) => {
  //   let {key, value} = payload
  //   dispatch({
  //     type: `${namespace}/inputChange`,
  //     payload: {
  //       ...payload
  //     }
  //   })
  // }
  //
  function changeUrl(state, i, status) {

  }
  function saveUrl(url) {

  }
  function delImg(i) {

  }
  function saveBanner(i) {
  
  }
  function removeImgUrl(index) {

  }
  function updateImageModel(value, i) {

  };
  //输入框改变时
  function inputChange(value, key, idx) {
    set(formData,key,value,'')
    dispatch({
      type: namespace + '/updateStore',
      payload: {obj }
    });
    console.log(e, type);
  }
  function onChange(pageNo, pageSize) {
    pageInfo[channelIndex].pageNo=pageNo
    pageInfo[channelIndex].pageSize=pageSize
    changeState({ pageInfo });
    dispatch({ type: `${namespace}/getBannerList`, payload: { pageNo: pageNo, pageSize: pageSize } });
    console.log(pageNo, pageSize);
  }
  return (
    <div className={cx('pageLayout')}>
      <div className="public_listMain">
        <div className="functionButton">
          <Tooltip title="最多只能导出15000条数据" placement={'topRight'}>
            <Button type="primary"  loading={modelObj.exportLoading} onClick={() =>{
              dispatch({
                type: `${namespace}/exportFile`,
                payload: {}
              })
            }}>导出</Button>
          </Tooltip>

        </div>
        <AdvanceSearch
          footer={
            <span>
                <Button type="primary" htmlType="submit" onClick={() => onSearch()} loading={loading}>搜索</Button>
                <Button onClick={() => dispatch({ type: `${namespace}/queryReset` })}>重置</Button>
              </span>
          }
        >
          <QueryCondition
            data={queryList}
            inputChange={(key, value) => dispatch({type: `${namespace}/inputChange`, payload: {key, value}})}
          />
        </AdvanceSearch>
        {/* 表格区域 */}
        <CollapsiblePanels title="轮播图">
          <Row  type="flex" justify="space-between" gutter={16}>
            {
              bannerList['1'] && bannerList['1'].map((item, index) => {
                return (
                  <Col  className={cx('mgb2','flex1')} style={{minWidth:'45%'}}>
                    <div className={cx('flex','flex_center_h','li')}>
                      <div className="pd1">
                        {`图${index+1}`}
                      </div>
                      <div className="imgBox">
                        <Uploader uploadedUrls={item.url}
                          // imgUrlSize={'146'}
                                  removeFileCbf={(e) => { removeImgUrl(i) }}
                                  uploadSuccessCbf={(imgUrl) => { updateImageModel(imgUrl, i) }}
                                  showType={'3'}
                                  fileType='image'
                                  fileMaxSize='0.3'
                                  minCropBoxWidth={1372}
                                  minCropBoxHeight={736}
                                  maxFiles='1' />
                      </div>
                      <div className="flex1 pdr1">
                        <Row>
                          <Col span={4} style={{textAlign:'right'}}>链接</Col>
                          <Col span={20}>
                            <Tooltip placement="topLeft" title="链接地址：（链接请加上传输协议，如http://或https://）">
                              <a href='javascript:void(0);' className={cx('item_link')} alt={item.href||''}>{item.href ? item.href : '暂无链接...'}</a>
                            </Tooltip>
                          </Col>
                        </Row>
                        {/*<FormItem {...formItemLayout} label="链接" >*/}
                          {/*<Tooltip placement="topLeft" title="链接地址：（链接请加上传输协议，如http://或https://）">*/}
                            {/*<a href='javascript:void(0);' className={cx('item_link')} alt={item.href||''}>{item.href ? item.href : '暂无链接...'}</a>*/}
                          {/*</Tooltip>*/}
                        {/*</FormItem>*/}
                        <FormItem {...formItemLayout01} label="序号" >
                          {getFieldDecorator(`order_${item.slideshowId}`, {
                            initialValue: item.ord,
                          })(<Input
                            // style={{ width: '160px' }}
                            // placeholder={'请输入序号'}
                            onChange={(e) => {set(bannerList,'[1]['+index+'].ord',e.target.value);changeState({bannerList}) }}
                          />)}
                        </FormItem>
                      </div>
                      <div className={cx('center','btns')} >
                        <div className="mgb1">
                          <Button className={styles.oBannerRightBtn} onClick={() => { changeUrl({ oVisible: true }, i) }}>
                            {item.href ? '更改' : '添加'}链接
                          </Button>
                        </div>
                        <div className="mgb1">
                          <Popconfirm placement="top" title={"确定删除当前广告轮播图吗？"} onConfirm={() => delImg(i)} okText="确定" cancelText="取消">
                            <Button>删除</Button>
                          </Popconfirm>
                        </div>
                        <div className="mgb1">
                          <Button type="primary"  onClick={() => { saveBanner(i) }}>保存</Button>
                        </div>
                      </div>
                    </div>
                  </Col>
                )
              })
            }
            
          </Row>
          {/* 添加用户 */}
          {/*<Grid {...gridProps} />*/}
          <Row className={'clearfix'}>
            <Col className={'fr'}>
              <Pagination onChange={onChange}  total={Number(pageInfo[channelIndex]['total']||0)} showSizeChanger showQuickJumper />
            </Col>
          </Row>
        </CollapsiblePanels>
        <Modal
          title={'详情'}
          width='80%'
          // className="pubBiz_CommonModel"
          visible={modalObj.visible}
          onCancel={() => {updateModal()}}
          footer={null}
        >
        </Modal>
      </div>
    </div>
  )
}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(routeView))

